package com.nf.nf.common.support;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.nf.nf.util.ResourceUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Api接口返回报文封装类
 *
 * @author 章隆敏
 * @version [1.0, 2017年1月14日]
 */
public class ApiData {
    /**
     * 请求状态 1、为成功，默认为1
     */
    private Integer result = 1;
    /**
     * 返回消息如报错信息等
     */
    private String msg;
    /**
     * 报文参数
     */
    private Object data;

    public ApiData() {
        this.setResult(1);
    }

    public ApiData(Integer result, String msg, Object data) {
        this.setResult(result);
        this.msg = msg;
        this.data = data;
    }

    public Integer getResult() {
        return result;
    }

    public void setResult(Integer result) {
        this.result = result;
        // 已经设置过错误信息的则不需再按照编码解析
        if (StringUtils.isNotEmpty(msg) && !"success".equals(this.msg)) {
            return;
        }
        this.setMsg(ResourceUtil.getErrorByCode(result.toString()));
    }

    public void setResult(Integer result, String fields[]) {
        this.result = result;
        // 已经设置过错误信息的则不需再按照编码解析
        if (StringUtils.isNotEmpty(msg) && !"success".equals(this.msg)) {
            return;
        }
        String m = ResourceUtil.getErrorByCode(result.toString());
        for (int i = 1; i <= fields.length; i++) {
            String flag = "\\{" + i + "\\}";
            m = m.replaceAll(flag, fields[i - 1]);
        }
        this.setMsg(m);
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static String replace(final String sourceString, Object[] object) {
        String temp = sourceString;
        for (int i = 0; i < object.length; i++) {
            String result = (String) object[i];
            Pattern pattern = Pattern.compile("");
            Matcher matcher = pattern.matcher(temp);
            temp = matcher.replaceAll(result);
        }
        return temp;
    }

}
